package top.chaileilei.zookeeper.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

/**
 * @Description 分布式锁demo
 * @Time 2019/2/12
 * @Author CHAILEILEI
 * @Weblog www.chaileilei.top
 */
public class LockDemo {
    private static String path = "/dgfght";
    private static CuratorFramework client = CuratorFrameworkFactory.builder()
            .connectString("119.27.189.174:2181")
            .sessionTimeoutMs(5000)
            .retryPolicy(new ExponentialBackoffRetry(1000, 3))
            .build();


    public static void lock(){
        client.start();
        final InterProcessMutex lock = new InterProcessMutex(client,path);
        final CountDownLatch countDownLatch = new CountDownLatch(1);
        for(int i = 0; i < 30; i++){
            new Thread(new Runnable() {
                public void run() {
                    try {
                        countDownLatch.await();
                        lock.acquire();
                    } catch ( Exception e ) {}
                    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss|SSS");
                    String orderNo = sdf.format(new Date());
                    System.out.println("生成的订单号是 : "+orderNo);
                    try {
                        lock.release();
                    } catch ( Exception e ) {}
                }
            }).start();
        }
        countDownLatch.countDown();
    }


}
